package com.polaris.live.ui.live.proxy

import android.view.TextureView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.ui.live.widget.listener.OnPlayFirstFrameListener
import com.polaris.live.ui.live.widget.listener.OnPublishFirstFrameListener
import com.polaris.live.utils.zego.LiveActivityIdentifier
import com.polaris.live.utils.zego.LiveEngineManage
import com.polaris.live.utils.zego.LivePlayer
import com.polaris.live.utils.zego.beauty.OnFaceStateChangeListener
import im.zego.zegoexpress.ZegoExpressEngine
import im.zego.zegoexpress.callback.IZegoEventHandler
import im.zego.zegoexpress.constants.ZegoPublishChannel
import im.zego.zegoexpress.constants.ZegoStreamResourceMode
import im.zego.zegoexpress.constants.ZegoVideoMirrorMode

/**
 * 流管理器
 *
 * @author Created by lucas on 2023/11/10 15:31
 */
class LiveStreamProxy(
    private val face: LiveActivityIdentifier,
    private val owner: LifecycleOwner,
    private val viewModel: BaseViewModel,
    private val engine: ZegoExpressEngine,
    private val publishView: TextureView,
    private val playView: TextureView,
    private val smallView: TextureView = playView,
    private val onPublishFirstFrameListener: OnPublishFirstFrameListener,
    private val onPlayFirstFrameListener: OnPlayFirstFrameListener,
    private val onFaceStateChangeListener: OnFaceStateChangeListener?,
) {

    private var nowPlayView = playView
    private val liveEngineProxy =
        LiveEngineProxy(
            owner,
            engine,
            viewModel,
            onFaceStateChangeListener,
        )

    private var currentSmallView: TextureView = smallView

    private var currentPublishSteamId: String? = null
    private var currentPlaySteamId: String? = null

    //摄像头的状态  true是前置  false是后置
    private var cameraType = true

    private val eventHandler = object : IZegoEventHandler() {
        override fun onPublisherRenderVideoFirstFrame(channel: ZegoPublishChannel?) {
            onPublishFirstFrameListener.onPublishFirstFrame()
        }

        override fun onPlayerRenderVideoFirstFrame(streamID: String?) {
            if (streamID != null && streamID == currentPlaySteamId) {
                onPlayFirstFrameListener.onPlayFirstFrame()
            }
        }

    }

    init {
        LiveEngineManage.eventHandlerHelper.addEventHandler(eventHandler)

        owner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                when (event) {
                    Lifecycle.Event.ON_DESTROY -> {
                        LiveEngineManage.eventHandlerHelper.removeEventHandler(eventHandler)

                        stopPublishStream()

                        stopPlayStream()
                    }

                    else -> {
                    }
                }
            }
        })
    }

    /**
     * 本地设备检测
     */
    fun localDeviceTest() {
        engine.startPreview()
        engine.startSoundLevelMonitor()
    }

    /**
     * 仅浏览
     */
    fun startPreview() {
        liveEngineProxy.startPreview(publishView)
    }

    /**
     * 使用前置摄像头
     */
    fun userFrontCamera() {
        cameraType = false
        changeCamera()
    }

    /**
     * 开始推流，也是切换流
     */
    fun startPublishStream(streamId: String) {
        liveEngineProxy.startPublish(streamId, publishView)
        engine.useFrontCamera(true)
        currentPublishSteamId = streamId
    }

    /**
     * 恢复推流
     */
    fun resumePublishStream(streamId: String) {
        startPreview()
        liveEngineProxy.resumePublish(streamId)
        if (cameraType) {
            engine.setVideoMirrorMode(ZegoVideoMirrorMode.ONLY_PREVIEW_MIRROR)
        } else {
            engine.setVideoMirrorMode(ZegoVideoMirrorMode.NO_MIRROR)
        }
    }

    /**
     * 暂停推流
     */
    fun pausePublishStream() {
        liveEngineProxy.pausePublish()
    }

    /**
     * 停止推流
     */
    fun stopPublishStream() {
//        if (currentPublishSteamId != null) {
        liveEngineProxy.stopPublish()
//        }

        currentPublishSteamId = null
    }

    fun initiativeStopPublishStream() {
        liveEngineProxy.initiativeStopPublish()
    }

    /**
     * 播放流
     */
    fun startPlayStream(streamId: String) {
        //call播放的是rtc
        LivePlayer.startLive(
            streamId,
            nowPlayView,
            face,
            false,
            null,
            ZegoStreamResourceMode.ONLY_RTC
        )
        currentPlaySteamId = streamId
    }

    /**
     * 停止播放流
     */
    fun stopPlayStream() {
        currentPlaySteamId?.also {
            LivePlayer.stopLive(nowPlayView)
        }
        currentPlaySteamId = null
    }

    /**
     * 重置浏览
     */
    fun resetPreview() {
        liveEngineProxy.switchPreview(publishView)

        nowPlayView = smallView

        currentSmallView = smallView
    }

    /**
     * 切换大小窗
     *
     * @param nextBigView 准备切换为大窗的view
     */
    fun switchPlayView(nextBigView: TextureView? = null) {
        //如果是小窗则将其切换
        val currentPlaySteamId = currentPlaySteamId ?: return

        val bigTextureView: TextureView
        val smallTextureView: TextureView

        if (nextBigView != null) {
            if (currentSmallView == nextBigView) {
                if (nextBigView != publishView) {
                    bigTextureView = publishView
                    smallTextureView = playView
                } else {
                    bigTextureView = playView
                    smallTextureView = publishView
                }
            } else {
                return
            }
        } else if (currentSmallView == playView) {
            bigTextureView = playView
            smallTextureView = publishView
        } else {
            bigTextureView = publishView
            smallTextureView = playView
        }
        nowPlayView = bigTextureView

        LivePlayer.startLive(
            currentPlaySteamId,
            nowPlayView,
            face,
            false,
            null,
            ZegoStreamResourceMode.ONLY_RTC
        )

        liveEngineProxy.switchPreview(smallTextureView)

        currentSmallView = smallTextureView
    }

    /**
     * 切换摄像头
     */
    fun changeCamera() {
        cameraType = !cameraType
        engine.useFrontCamera(cameraType)
        if (cameraType) {
            engine.setVideoMirrorMode(ZegoVideoMirrorMode.ONLY_PREVIEW_MIRROR)
        } else {
            engine.setVideoMirrorMode(ZegoVideoMirrorMode.NO_MIRROR)
        }
    }

    /**
     * 设置游戏视频通话控件
     * publishView 自己的流
     * playView 对方的流
     */
    fun setStartGameCallView(publishView: TextureView, playView: TextureView) {
        currentPlaySteamId?.let {
            //call播放的是rtc
            LivePlayer.startLive(
                it,
                playView,
                face,
                false,
                null,
                ZegoStreamResourceMode.ONLY_RTC
            )
        }
        liveEngineProxy.startPreview(publishView)
    }

    fun onGameOpenCloseCamera(mCloseCamera: Boolean, publishView: TextureView) {
        if (mCloseCamera) {
            liveEngineProxy.stopPublish()
        } else {
            currentPublishSteamId?.let {
                liveEngineProxy.startPublish(it, publishView)
            }
        }
    }

    fun onGameOtherOpenCloseCamera(mCloseCamera: Boolean, publishView: TextureView) {
        if (mCloseCamera) {
            currentPlaySteamId?.also {
                LivePlayer.stopLive(it)
            }
        } else {
            currentPlaySteamId?.let {
                //call播放的是rtc
                LivePlayer.startLive(
                    it,
                    publishView,
                    face,
                    false,
                    null,
                    ZegoStreamResourceMode.ONLY_RTC
                )
            }
        }
    }
}